# -*- coding: utf-8 -*-
# @Author: 16601513301
# @Date:   2025-09-24 16:56:28
# @Last Modified by:   18860233105
# @Last Modified time: 2025-09-24 18:26:15
# 获取cookie
from setting import *
from weibo_login_cookie import *
from weibo_user_info import *
import myglobal
import random
import json

# 全局变量记录当前有效的type
_current_valid_type = None

# weibo_cookies.json
def getweiboCookie():
    with open(COOKIE_PATH, mode="r",encoding="utf-8") as f:
        cookies = f.read()
    return cookies

# cookies.json
def getweiboCookie2():
    with open(COOKIE_PATH2, mode="r",encoding="utf-8") as f:
        cookies = f.read()
    return cookies  

def validate_cookie(cookies):
    """
    验证Cookie是否有效
    Returns: bool - True表示有效，False表示无效
    """
    try:
        # 这里可以添加具体的Cookie验证逻辑
        # 例如：尝试访问一个需要登录的页面，检查返回状态
        if not cookies or len(cookies) == 0:
            return False
        
        # 简单的验证：检查必要的Cookie字段是否存在
        required_fields = ['SUB', 'SUBP', 'XSRF-TOKEN']
        for field in required_fields:
            if field not in cookies:
                return False
        
        return True
    except Exception as e:
        print(f"Cookie验证失败: {e}")
        return False

def get_cookie(type=None):
    """
    获取微博Cookie，支持失败重试机制
    
    Args:
        type: 获取方式类型
            1: 从COOKIE_PATH文件读取
            2: 使用get_specific_cookies获取并保存
            3: 从用户信息获取随机Cookie
            4: 使用硬编码的Cookie
            None: 使用当前有效类型或随机选择
    
    Returns:
        dict: Cookie字典
    """
    global _current_valid_type
    
    # 如果之前有有效的type，优先使用
    if type is None and _current_valid_type is not None:
        type = _current_valid_type
        print(f"使用之前有效的type: {type}")
    elif type is None:
        type = random.randint(1, 5)
        print(f"随机选择type: {type}")
    
    max_retries = 3  # 最大重试次数
    retry_count = 0
    
    while retry_count < max_retries:
        try:
            cookies = {}
            
            if type == 1:
                cookie_str = getweiboCookie()
                try:
                    cookies = json.loads(cookie_str)
                except json.JSONDecodeError as e:
                    print(f"JSON解析错误: {e}")
                    cookies = {}
                    
            elif type == 2:
                cookie_str = getweiboCookie2()
                try:
                    cookies = json.loads(cookie_str)
                except json.JSONDecodeError as e:
                    print(f"JSON解析错误: {e}")
                    
            elif type == 3:
                user_id = myglobal.user_id
                cookies = get_weibo_rand_cookie(user_id=user_id)
                
            elif type == 4:
                cookies = {
                    '_T_WM': "91527798931",
                    'ALF': "1761291802",
                    'M_WEIBOCN_PARAMS': "uicode=20000174",
                    'MLOGIN': "1",
                    'mweibo_short_token': "a7ab137f28",
                    'SCF': "AsruMd9nHNgofQjdMUQgnQ1AKoIEeQgIkAnA2A8gbw3Ygzps2ynSGWb1_Ng5H8-qpH6d4XezBnUIkHthNYxvRjw.",
                    'SUB': "_2A25F19FKDeRhGeFG7VQS-SbOzzuIHXVmrWyCrDV6PUJbktANLWPTkW1NeQJaMX1CNfnL4iLR8J3MIsjazsLKQXwx",
                    'SUBP': "0033WrSXqPxfM725Ws9jqgMF55529P9D9WWoridYzWcD1oFrYREC-0yO5JpX5KMhUgL.FoMRSoq01KnEShM2dJLoIp7LxK.L1KMLBo.LxK.L1KMLBo._i--Xi-iFi-iF",
                    'WEIBOCN_FROM': "1110006030",
                    'XSRF-TOKEN': "9574fe",
                }
            elif type == 5:
                target_cookies = get_specific_cookies()
                print(f"✅ cookie已成功保存到文件: weibo_cookies.json")
                cookie_str = getweiboCookie2()
                try:
                    cookies = json.loads(cookie_str)
                except json.JSONDecodeError as e:
                    print(f"JSON解析错误: {e}")
            else:
                print(f"无效的type: {type}")
                type = random.randint(1, 5)
                retry_count += 1
                continue
            
            # 验证Cookie是否有效
            if validate_cookie(cookies):
                _current_valid_type = type  # 记录当前有效的type
                print(f"✅ type {type} 获取Cookie成功")
                return cookies
            else:
                print(f"❌ type {type} 获取的Cookie无效，尝试其他类型")
                type = get_next_type(type)
                retry_count += 1
                
        except Exception as e:
            print(f"❌ type {type} 获取Cookie时发生错误: {e}")
            type = get_next_type(type)
            retry_count += 1
    
    # 所有重试都失败，返回空Cookie
    print("❌ 所有获取方式都失败，返回空Cookie")
    return {}

def get_next_type(current_type):
    """获取下一个要尝试的type"""
    next_type = current_type + 1
    if next_type > 5:
        next_type = 1
    print(f"切换到下一个type: {next_type}")
    return next_type

def rand_cookie():
    """随机获取Cookie（带失败重试机制）"""
    return get_cookie(type=None)

# 测试函数
def test_cookie_validation():
    """测试Cookie验证功能"""
    test_cookies = [
        {'SUB': 'test', 'SUBP': 'test', 'XSRF-TOKEN': 'test'},  # 有效
        {},  # 无效
        {'SUB': 'test'},  # 无效（缺少必要字段）
    ]
    
    for i, cookie in enumerate(test_cookies):
        result = validate_cookie(cookie)
        print(f"测试 {i+1}: {result}")

if __name__ == "__main__":
    # 测试
    print("=== 测试Cookie获取 ===")
    cookie = rand_cookie()
    print(f"获取到的Cookie: {cookie}")
    
    print("\n=== 测试Cookie验证 ===")
    test_cookie_validation()
